LeetCode11
LeetCode 第11题的分析和总结
题目描述:
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container,
such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
In this case, the max area of water (blue section)
the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
思路清晰,这道题和原来的不同:
y
^
|
| a2
| | a3 an
| a1 | | a5 |
| | | | a4 | |
| | | | | | .. |
--------------------------->
0 1 2 3 4 5 .. n x
只是为了寻找两个位置i,j 组成的桶,能够形成一个最大的容器,而不是这个题目:https://leetcode.com/problems/trapping-rain-water/
这就是一个“双指针”移动的问题。
代码:
public static int max(int[] A) {
int S = 0, i = 0, j = A.length -1;
while (i < j) {
S = Math.max(S, (j - i) * Math.min(A[i], A[j]));
if (A[i] < A[j]) i++; else j--;
}
return S;
}
- 上一篇 LeetCode09
- 下一篇 LeetCode10